<template>
  <a-row>
    <div class="total-table-container">
      <a-row style="margin-bottom: 8px;">
        <a-col :span="2" push="22" style="text-align: right;">
          <ExportFile
            :fetch="getDownloadData"
            :fields="jsonFields"
            name="downloadFile.xls"
          >
            <a-button
              class="editable-add-btn"
              type="primary"
              :loading="iconLoading"
              >导出</a-button
            >
          </ExportFile>
        </a-col>
      </a-row>

      <a-row>
        <a-table
          :columns="tableColumns"
          :data-source="tableDataLists"
          :scroll="{ x: 1200 }"
          :rowKey="
            (record, index) => {
              return index;
            }
          "
          :customRow="clickSingleRow"
          :pagination="paginationOpt"
          :loading="isLoading"
          bordered
        >
          <template slot="afterSaleNumber" slot-scope="text, record, index">
            <div class="editable-row-operations">
              <span
                v-if="record.afterSaleService.afterSaleNumber === ''"
                class="update-button"
              >
                <img src="@/images/agent_service.png" />
              </span>
              <span
                v-if="record.afterSaleService.afterSaleNumber !== ''"
                class="update-button"
              >
                <img src="@/images/agent_service.png" />&nbsp;&nbsp;<img
                  src="@/images/hzncc_service.png"
                />
              </span>
            </div>
          </template>

          <template slot="state" slot-scope="text, record, index">
            <div class="editable-row-operations">
              <span v-if="record.repairList.state === 1">已报单</span>
              <span v-if="record.repairList.state === 2">已指派</span>
              <span v-if="record.repairList.state === 8">进行中</span>
              <span v-if="record.repairList.state === 9">工单暂停</span>
              <span v-if="record.repairList.state === 5">待回访</span>
              <span v-if="record.repairList.state === 6">已关闭</span>
              <span v-if="record.repairList.state === 4">已关闭</span>
              <span v-if="record.repairList.state === 10">内部已关闭</span>
              <span v-if="record.repairList.state === 11">已指派</span>
            </div>
          </template>
        </a-table>
      </a-row>
    </div>
  </a-row>
</template>

<script>
import api from "@/server/userConfig";
import { columns, buildTableData } from "./tableConfig";
import ExportFile from "vue-json-excel";

function buildJsonFields(lists) {
  let jsonFields = {};
  lists.forEach((item, index) => {
    if (item.dataIndex) {
      jsonFields[item.title] = item.dataIndex;
    }
  });
  return jsonFields;
}

export default {
  name: "HistoryOrderTable",
  props: {
    searchData: Object
  },
  components: {
    ExportFile
  },
  data() {
    return {
      username: "",
      tableColumns: columns,
      tableDataLists: [],
      isLoading: false,
      paginationOpt: {
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 8, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        // showSizeChanger: true,
        // showQuickJumper: true,
        // pageSizeOptions: ["10", "20", "30", "40"],
        showTotal: total => `共 ${total} 条`, // 显示总数
        // 点击选择每页多少条时事件
        // onShowSizeChange: (current, pageSize) => {
        //   this.paginationOpt.defaultCurrent = 1;
        //   this.paginationOpt.defaultPageSize = pageSize;
        // },
        // 点击分页时事件
        onChange: (current, size) => {
          let _this = this;
          this.paginationOpt.defaultCurrent = current;
          this.getCompletedRepairOrderByPage(
            {
              username: _this.username,
              pageIndex: current,
              pageSize: _this.paginationOpt.defaultPageSize
            },
            "tableDataLists"
          );
        }
      },
      iconLoading: false,
      jsonFields: buildJsonFields(columns)
    };
  },
  computed: {},
  watch: {
    searchData: function(newVal, oldVal) {
      let _this = this;
      _this.getData({ pageIndex: this.paginationOpt.defaultCurrent });
    }
  },
  created() {
    // 获取链接参数username值，然后存进内存中
    this.username = localStorage.getItem("phone");
  },
  mounted() {
    this.getRoleId();
    this.getData({ pageIndex: 1 });
  },
  methods: {
    getData(parames) {
      this.getCompletedRepairOrderByPage(parames, "tableDataLists");
    },
    // Table 获取数据
    async getCompletedRepairOrderByPage(parames, key) {
      let _this = this;
      _this.isLoading = true;
      const res = await api.getCompletedRepairOrderByPage({
        pageIndex: _this.paginationOpt.defaultCurrent,
        pageSize: _this.paginationOpt.defaultPageSize,
        username: _this.username,
        ..._this.searchData,
        ...parames
      });

      _this.isLoading = false;

      if (res.MsgCode !== 0) {
        return;
      }

      this.paginationOpt.total = res.Data.total;

      let newObj = res.Data.content;
      this[key] = newObj;
    },

    // 点击每一行的跳转;
    clickSingleRow(record, index) {
      return {
        on: {
          click: () => {
            // 实现跳转;
            if (record.afterSaleService.afterSaleNumber !== "") {
              window.open(
                `/#/saleDetail?orderNumber=${record.repairList.repairOrderNumber}&saleNumber=${record.afterSaleService.afterSaleNumber}&suit=${record.suit}`
              );
            } else {
              window.open(
                `/#/clientDetail?orderNumber=${record.repairList.repairOrderNumber}`
              );
            }
          }
        }
      };
    },

    // 根据登陆的手机号获取角色id;
    async getRoleId() {
      if (this.username !== "") {
        const res = await api.getRoleId({ phoneNumber: this.username });
        if (res.MsgCode !== 0) {
          return;
        }
        const roleId = res.Data.ID;
        this.role = roleId;
      }
    },

    // 获取需要导出的数据
    async getDownloadData() {
      let _this = this;
      if (_this.iconLoading == true) {
        return false;
      }
      let total = _this.paginationOpt.total;
      let pageSize = 300;
      let length = Math.ceil(total / pageSize);
      let newLists = [];
      _this.iconLoading = true;
      for (let i = 1; i <= length; i++) {
        let lists = await this.buildDownloadLists({
          pageIndex: i,
          pageSize: pageSize
        });
        newLists.push(lists);
      }
      _this.iconLoading = false;
      return [].concat(...newLists);
    },

    async buildDownloadLists(parames) {
      let _this = this;
      const res = await api.getCompletedRepairOrderByPage({
        username: _this.username,
        ..._this.searchData,
        ...parames
      });

      if (res.MsgCode !== 0) {
        return;
      }
      let list = buildLists(res.Data.content);
      return list;

      function buildLists(lists) {
        return lists.map((item, index) => {
          try {
            let newItem = format(item);
            return newItem;
          } catch (e) {
            console.log(e);
          }
        });
      }

      function format(item) {
        if (item.repairList && item.repairList.repairOrderNumber) {
          item.repairList.repairOrderNumber = `'${item.repairList.repairOrderNumber}'`;
        }
        if (item.repairList && item.repairList.state) {
          item.repairList.state = formatState(item.repairList.state);
        }
        if (item.evaluation && item.evaluation.serviceScore) {
          item.evaluation.serviceScore += "分";
        }
        if (item.evaluation && item.evaluation.produceScore) {
          item.evaluation.produceScore += "分";
        }

        return item;
      }

      function formatState(state) {
        switch (state) {
          case 1:
            return "已报单";
          case 2:
            return "已指派";
          case 4:
            return "已关闭";
          case 5:
            return "待回访";
          case 6:
            return "已关闭";
          case 8:
            return "进行中";
          case 9:
            return "工单暂停";
          case 10:
            return "内部已关闭";
          case 11:
            return "已指派";
          default:
            break;
        }
      }
    }
  }
};
</script>

<style lang="css" scoped>
@import "./style.css";
</style>
